package com.report.service;

import com.schedule.domain.ReportRule;
import com.schedule.domain.ResultRealtimeCollector;
import com.schedule.domain.Template;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.internal.NativeQueryImpl;
import org.hibernate.transform.Transformers;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.Iterator;
import java.util.List;

/**
 * 加载数据
 */

@Service("reportLoadDataService")
public class ReportLoadDataService {


    @Autowired
    EntityManagerFactory entityManagerFactory;

    @Transactional
    public List<ResultRealtimeCollector> loadData(String sql){
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try {

            Query query = entityManager.createNativeQuery(sql)
                    .unwrap(NativeQuery.class)
                    .addScalar("resId", StandardBasicTypes.STRING)
                    .addScalar("resName", StandardBasicTypes.STRING)
                    .addScalar("kpiId", StandardBasicTypes.STRING)
                    .addScalar("kpiName", StandardBasicTypes.STRING)
                    .addScalar("kpiValue", StandardBasicTypes.STRING)
                    .addScalar("flag", StandardBasicTypes.STRING)
                    .addScalar("ip", StandardBasicTypes.STRING)
                    .addScalar("resType", StandardBasicTypes.STRING)
                    .addScalar("os", StandardBasicTypes.STRING)
                    /*.addScalar("version", StandardBasicTypes.STRING)
                    .addScalar("admin", StandardBasicTypes.STRING)
                    .addScalar("busName", StandardBasicTypes.STRING)
                    .addScalar("busIp", StandardBasicTypes.STRING)
                    .addScalar("managerIp", StandardBasicTypes.STRING)
                    .addScalar("hostName", StandardBasicTypes.STRING)*/;

            query.unwrap(NativeQueryImpl.class).setResultTransformer(Transformers.aliasToBean(ResultRealtimeCollector.class));
            List<ResultRealtimeCollector> resultList = query.getResultList();
            if (resultList != null) {
                return resultList;
            }
            return null;
        }finally {
            EntityManagerFactoryUtils.closeEntityManager(entityManager);
        }
    }
}
